<script setup lang="ts">

import {
  azureClientId,
  azureOAuthRoute, azureScope,
  azureSSOUrl, createAzureLoginURL, parseAzureLoginResponse
} from "@/utils/cloudService/azure";
import {ImportBookmarkType, initBrowserError, onedrive, Option, SyncMethod} from "@/utils/constants";
import {User} from "@element-plus/icons-vue";
import SettingItem from "@/components/SettingItem.vue";
import {SyncServiceSetting} from "@/utils/config";
import {changeCronSyncTime, changeSyncServiceSyncStatus, saveConfig} from "@/utils/componentUtils";
import {ShallowRef, toRaw} from "vue";
import {browserDriver, config} from "@/store/modules/globals";


const cronSyncOptions: Option[] = [
  {
    value: null,
    label: '不同步'
  },
  {
    value: 0.5,
    label: '30秒'
  },
  {
    value: 1,
    label: '1分钟'
  },
  {
    value: 5,
    label: '5分钟'
  },
  {
    value: 15,
    label: '15分钟'
  },
  {
    value: 30,
    label: '30分钟'
  },
  {
    value: 60,
    label: '1小时'
  },
  {
    value: 4 * 60,
    label: '4小时'
  },
  {
    value: 8 * 60,
    label: '8小时'
  },
  {
    value: 1440,
    label: '1天'
  }
];
const syncMethodOptions: Option[] = Object.entries(SyncMethod).map(([key, value]) => (
    key !== "default" ? {"value": key, "label": value, "disable": value === SyncMethod.sync} : null
)).filter(item => !!item) as Option[];
const oneDriveSetting: SyncServiceSetting = toRaw(config.syncServiceSettingMap.value.onedrive);

const token: ShallowRef<string | null | undefined> = oneDriveSetting._token;
const canEnable: ShallowRef<boolean> = oneDriveSetting.canEnable;


// console.log("oneDriveSetting", oneDriveSetting);
// console.log("oneDriveSetting.syncMethod.value", oneDriveSetting.syncMethod.value);
// console.log("SyncMethod.cron", SyncMethod.cron);
// console.log("oneDriveSetting.syncMethod.value === SyncMethod.cron", oneDriveSetting.syncMethod.value === SyncMethod.cron);


if (!browserDriver.ssoAuthLogin) {
  throw initBrowserError;
}
const ssoAuthLogin = browserDriver.ssoAuthLogin;


/**
 * 登录
 */
function authLogin() {
  let result = ssoAuthLogin(
      createAzureLoginURL,
      azureOAuthRoute,
      parseAzureLoginResponse,
  );
  if (result instanceof Promise) {
    result.then((token) => {
      if (!token) {
        return;
      }
      // console.log("oneDriveSetting", oneDriveSetting);
      // console.log("token", token);
      oneDriveSetting.token = token;
      saveConfig();
    })
  }
  else {
    // console.log("oneDriveSetting", oneDriveSetting);
    // console.log("token", result);
    oneDriveSetting.token = result;
    saveConfig();
  }
}


/**
 * 登出
 */
function authLogout() {
  oneDriveSetting.token = null;
  saveConfig();
}

/**
 * 点击登陆录按键
 */
function clickLoginBtn() {
  // console.log("oneDriveSetting.token.value", oneDriveSetting.token.value);
  if (!oneDriveSetting.token.value) {
    authLogin();
  }
  else {
    authLogout();
  }
  // console.log("点击登陆录按键后 oneDriveSetting", oneDriveSetting);
}



/**
 * 改变同步方法
 * @param value
 */
function changeSyncMethodEvent(value: SyncMethod) {
  changeSyncServiceSyncStatus(onedrive, value, oneDriveSetting.cronSyncTime.value);
}


/**
 * 改变同步方法
 * @param value
 */
function changeCronSyncTimeEvent(value: number | null) {
  changeCronSyncTime(onedrive, value);
}
</script>

<template>
  <setting-item
      name="登录OneDrive"
      description="登录后才可使用OneDrive的同步功能"
  >
    <template #rightSlot>
      <el-button
          plain
          size="large"
          :icon="User"
          @click="clickLoginBtn"
          :disabled="canEnable && false"
      >
        {{ !token ? "登录" : "退出" }}
      </el-button>
    </template>
  </setting-item>
  <div v-if="canEnable">
    <setting-item
        name="启用OneDrive"
        description="是否启用OneDrive同步功能"
        :status="oneDriveSetting.enable"
        :statusChange="saveConfig"
    >
    </setting-item>
    <setting-item
        name="同步方式"
        description="当收藏夹发生变化时，立刻同步至OneDrive（当启用多个云存储服务时，只可选择其中一个开启实时同步）"
    >
      <template #rightSlot>
        <el-select
            v-model="oneDriveSetting.syncMethod.value"
            placeholder="不同步"
            size="large"
            style="width: 120px"
            @change="changeSyncMethodEvent"
        >
          <el-option
              v-for="item in syncMethodOptions"
              :key="item.label"
              :label="item.label"
              :value="item.label"
              :disabled="item.disable"
          />
        </el-select>
      </template>
    </setting-item>
    <setting-item
        name="定时同步"
        description="每隔定时时间同步一次书签数据"
        v-if="oneDriveSetting.syncMethod.value === SyncMethod.cron"
    >
      <template #rightSlot>
        <el-select
            v-model="oneDriveSetting.cronSyncTime.value"
            placeholder="不同步"
            size="large"
            style="width: 120px"
            @change="changeCronSyncTimeEvent"
        >
          <el-option
              v-for="item in cronSyncOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </template>
    </setting-item>
  </div>
</template>

<style scoped>

</style>